const express = require('express')
const router = express()
// const auth = require('../middleware/auth')

const handler = require('../router_handler/articles')

// 导入验证数据的中间件
const expressJoi = require('@escook/express-joi')
// 导入文章分类的验证模块
const {
    getArticleByCateSchema,
    getArticleByIdSchema,
    updateArticleSchema,
    addArticleSchema,
    deleteArticleSchema
 } = require('../schema/article')


// 获取所有文章
router.get('/getall', handler.getAllArticle)

// 根据专业类别查询所有文章
router.get('/getbycate/:id',expressJoi(getArticleByCateSchema), handler.getArticleByCate)

// 根据文章 ID 获取文章信息
router.get('/getbyid/:id', expressJoi(getArticleByIdSchema), handler.getArticleById)

// 根据文章内容或者标题检索文章
router.get('/getbysearch/:search', handler.getArticleBySearch);

// 修改
router.post('/update', expressJoi(updateArticleSchema), handler.updateArticle)

const multer = require("multer");
// 导入内置的路径模块
const path = require("path");
// 创建multer实例对象，通过dest属性指定文件的存放路径
const upload = multer({ dest: path.join(__dirname, "../public/uploads") });
const fs = require('fs')
// 新增
// upload.any()
router.post(
  "/add",
  upload.single("image"),
  (req, res, next) => {
    // 文件后缀
    var extname = path.extname(req.file.originalname);
    // 拼接新路径
    // var newPath = req.file.path + extname;
    // 赋给图片的名称用时间戳+随机数获取
    var randomName = Date.now() + parseInt(Math.random()*999) + parseInt(Math.random()*666);
    var newPath = req.file.destination + '\\' + randomName + extname;
    // console.log(newPath);
    // 重命名
    fs.renameSync(req.file.path, newPath, (err) => {
      if(err) res.show("图片重命名失败！");
    })
    req.body.image = "/uploads/" + randomName + extname;
    next();
  },
  handler.addArticle
);

  // 删除
router.get(
    "/delete/:id",
    expressJoi(deleteArticleSchema),
    handler.deleteArticle
);





module.exports = router